import core.buffer.Buffer;
import game.Player;
import game.Scene;
import core.net.NetConfig;
import core.net.TCPServer;
import core.net.protocol.FrameCheckP;
import core.net.protocol.IProtocol;
import core.net.protocol.MoveP;
import core.net.protocol.Protocol;

import java.util.concurrent.atomic.AtomicInteger;

public class ServerApp {

    public static Scene scene;
    private static AtomicInteger _frame = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {

        Protocol.instance().register(FrameCheckP.TYPE, FrameCheckP.class);
        Protocol.instance().register(MoveP.TYPE, MoveP.class);
        NetConfig config = new NetConfig(5000, 32, 10*1000);
        TCPServer server = new TCPServer(32145,config);
        scene = new Scene();
        scene._handleCMD = ServerApp::handleCMD;
        server.connectedHandler(x->{
            Player player = new Player();
            player.connection(x);
            scene.entry(player);
            FrameCheckP fp = Protocol.instance().get(FrameCheckP.TYPE);
            fp.frame = _frame.get();
            player.send(fp);
        });
        server.open();

        while (true)
        {
            scene.update();
//            System.out.println("[update] frame " + _frame.get());
            _frame.incrementAndGet();
        }
    }

    public static void handleCMD(IProtocol protocol, Player player)
    {
        System.out.println("[receive] "+protocol);
            switch (protocol.protocolType())
            {
                case MoveP.TYPE -> {
                    Buffer buffer = Protocol.instance().serialize(protocol);
                    for (Player player1 : scene._playerList) {
                        player1.send(buffer);
                    }
                    Protocol.instance().put(protocol);
                }
            }
    }
}
